package org.karelun.rabbit.rcp.policy;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CompoundCommand;
import org.eclipse.emf.edit.command.CommandParameter;
import org.eclipse.emf.edit.command.CreateChildCommand;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.karelun.ideaboard.gef.editpolicies.GraphicalNodeEditPolicy;
import org.karelun.ideaboard.gef.requests.CreateConnectionRequest;
import org.karelun.ideaboard.gef.requests.ReconnectRequest;
import org.karelun.rabbit.graph.Connection;
import org.karelun.rabbit.graph.GraphPackage;
import org.karelun.rabbit.graph.Shape;

public class ShapeConnectionEditPolicy extends GraphicalNodeEditPolicy {

	@Override
	protected Command getConnectionCompleteCommand(CreateConnectionRequest request) {
		CompoundCommand ret = new CompoundCommand();
		ret.append(request.getStartCommand());

		Shape shape=(Shape)getHost().getModel();
		Connection connection = (Connection)request.getNewObject();
		Command setCommand = SetCommand.create(getEditingDomain(), connection, GraphPackage.Literals.CONNECTION__TARGET_SHAPE, shape);
		ret.append(setCommand);
		request.setStartCommand(ret);
		return ret;
	}

	@Override
	protected Command getConnectionCreateCommand(CreateConnectionRequest request) {
		Connection connection = (Connection)request.getNewObject();
		Object diagram = getHost().getParent().getModel();
		Shape shape=(Shape)getHost().getModel();
		
		CommandParameter descriptor = new CommandParameter(null, GraphPackage.Literals.DIAGRAM__CONNECTIONS, connection);
		List<Object> list=new ArrayList<Object>();
		list.add(diagram);
		CompoundCommand ret = new CompoundCommand();
		Command createCommand = CreateChildCommand.create(getEditingDomain(), diagram, descriptor, list);
		Command setCommand = SetCommand.create(getEditingDomain(), connection, GraphPackage.Literals.CONNECTION__SOURCE_SHAPE, shape);
		ret.append(createCommand);
		ret.append(setCommand);
		
		request.setStartCommand(ret);
		return ret;
	}

	@Override
	protected Command getReconnectTargetCommand(ReconnectRequest request) {
		Connection connection = (Connection)request.getConnectionEditPart().getModel();
		Shape targetShape=(Shape)getHost().getModel();
		return SetCommand.create(getEditingDomain(), connection, GraphPackage.Literals.CONNECTION__TARGET_SHAPE, targetShape);
	}

	@Override
	protected Command getReconnectSourceCommand(ReconnectRequest request) {
		Connection connection = (Connection)request.getConnectionEditPart().getModel();
		Shape sourceShape=(Shape)getHost().getModel();
		Command setCommand = SetCommand.create(getEditingDomain(), connection, GraphPackage.Literals.SHAPE__SOURCE_CONNECTIONS, sourceShape);
		return setCommand;
	}

	private EditingDomain getEditingDomain(){
		return getEditingDomain(getHost());
	}
}
